package com.hhck.controller;

import com.hhck.constants.Constants;
import com.hhck.dto.AuthGrantDto;
import com.hhck.entity.*;
import com.hhck.service.RoleService;
import com.hhck.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private TokenUtils tokenUtils;

    /**
     * 获取所有角色（已启用）
     */
    @GetMapping("/role-list")
    public Result roleList() {
        return Result.ok(roleService.queryAllRole());
    }

    /**
     * 分页查询所有角色（条件查询）
     */
    @GetMapping("/role-page-list")
    public Result rolePageList(Page page, Role role) {
        return Result.ok(roleService.queryRoleByPage(page, role));
    }

    /**
     * 添加角色
     */
    @PostMapping("/role-add")
    public Result roleAdd(@RequestBody Role role, @RequestHeader(Constants.HEADER_TOKEN_NAME) String token) {

        // 通过token解析当前用户
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        // 设置创建者（当前用户就是创建者）
        role.setCreateBy(currentUser.getUserId());

        return roleService.saveRole(role);
    }

    /**
     * 根据角色id启用或禁用角色
     */
    @PutMapping("/role-state-update")
    public Result roleStateUpdate(@RequestBody Role role) {
        return roleService.modifyRoleStateByRoleId(role);
    }

    /**
     * 根据角色id删除角色
     */
    @DeleteMapping("/role-delete/{roleId}")
    public Result roleDelete(@PathVariable Integer roleId) {

        try {
            // 发生异常事务自动回滚
            roleService.removeRoleByRoleId(roleId);
            return Result.ok("删除成功！");
        } catch (Exception e) {
            return Result.err(Result.CODE_ERR_BUSINESS, "删除失败！");
        }
    }

    /**
     * 根据角色id查询权限id
     */
    @GetMapping("/role-auth")
    public Result roleAuth(Integer roleId) {
        return Result.ok(roleService.queryRoleAuthIdListByRoleId(roleId));
    }

    /**
     * 给角色分配权限
     */
    @PutMapping("/auth-grant")
    public Result authGrant(@RequestBody AuthGrantDto authGrantDto) {

        try {
            roleService.saveRoleAuthByRoleId(authGrantDto.getRoleId(), authGrantDto.getAuthIds());
            return Result.ok("修改成功！");
        } catch (Exception e) {
            return Result.err(Result.CODE_ERR_BUSINESS, "修改失败！");
        }
    }

    /**
     * 根据角色id修改角色描述信息
     */
    @PutMapping("/role-update")
    public Result roleUpdate(@RequestBody Role role, @RequestHeader(Constants.HEADER_TOKEN_NAME) String token) {

        // 获取修改者
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        // 设置修改者
        role.setUpdateBy(currentUser.getUserId());

        return roleService.updateRoleDescByRoleId(role);
    }

}

